package com.lib.utls.pay;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.sdk.app.PayTask;
import com.lib.app.ARouterPathUtils;
import com.lib.fastkit.utils.permission.custom.PermissionUtil;
import com.lib.utls.pay.bean.PayResult;
import com.lib.utls.pay.tool.OrderInfoUtil2_0;


import java.util.Map;

/**
 * Created by chaohx on 2017/7/5.
 */

public class ZhiFuBaoPayUtils {


    private Activity context;
    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static final String APPID = "2019061265484925";
    /**
     * 应用私钥
     */
    public static final String RSA2_PRIVATE = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDZJAdLIJ5XXzeHc1JSODvaPS+L+6Np93gN2SQUzh3FJCL03tHX9L2yRpEuRajHpu+WdaXxKtwDPZwYtGOI+uL0oPiZmUoOP/Q61z796qH7AtrNxkVyQbFLmtiDlyorUA1I1RPUqiG6LQR5ted/973bqLSc86jXBYU7dmyYzx7yoN4J8hjCPHmlxkhnXd8yYZD43H592THDklLWIMW+vdu5u2j3qqWD0fKboUTmTwj8vrz0utJkInEQa219yMFhpB3SC/g0NZcw1p51ScMhbPDYxQwCMH+vy0P93+eUyoahqFr23WbX/1BZ18nY5KIOLMYFgta+eD1b2XwfpMqJwKfVAgMBAAECggEATn6KsGrTMox2G13h1V0ErejOZlEKCsVtvbvQIkE8W8araE+gFewgIvEFjG+cCsha9c4DtcGjlPxRkFCtZpgjMQF7vLLAJZSS6i5jVBDci0vF4vsYoawDtmv8dt1PXibrFngIWilCVfXuFz1duVHKbTx4RgCC+W/CcPNnYHoHGvfHrCvcLw8IKP10r5GBYpLJ+n7qdLPN7zqQ6H97a3Vh1FB0/pW1nm3ywQYCgNaE5o9C0xrJt876jpKE4kjCU5UrPk+kdpVA5cnpQ3brduPyY0aBx4OrBQ7WnJ8On1HmNpKG2emhD8Zs5N0ngZN4bz2yfVE6ghKrZXPPaEE39Du4pQKBgQDw8JxZftS27BLwY/efxIsAtQz4joSpyYh0B6punuxB7rlts6c3AGTrfEsfXtXXchwI18IRl8Hj2RpZJ5AmBKe95/DRCGs7zgPrHRLu4LOoWuJo65BKUJsmddLlSebDWPvOnE3i6rnY0e5BZm8BjVJTnM1VrrGSGT2AOwwqstZhuwKBgQDmtpi//7yz3gBZcHtXV2dHj3lTbsgdI7YJm4fFXZj8cT2uH2gV3znLq1P9lPKvlFZgy+vwelUB0L9QsHQNwqx9RMSUVutf0OHROrZe4eM/9qxvQ3nPSt/lkDOzrSQgjeubNPvScrp5wPdfCAtXUZ6pUCaGGAeeFix1eqC5+U17rwKBgQC9o7R8IH7Op0tU2Gor32fFG7vk21ABz3VOVkZIIWA1mO9sMA46FV5ZlxAN1fgcRl1YfHHspPTgIJ5DdAdaVSmuKKP781Nr1ABziwO+7y+ZIEe6a0a7p2wmvnBLNnqiYSR4/7+yDixPQxTzduuCXjhhRTa87O4o3yLwDgnKhc6FRwKBgFbCUbzZ6ddl45G+t9NHfgIuFPzoCv7SQBFq2GrC4NYFq6FAFD8tW6mYexRAH+chDD6IUOh0yGTPYDJyuKG4FG9jHd1+tjKo9VJeFtilb3TNSVjp8fOe/4VvbdHiiVRoqjIKgaxJEpDYnO2ys7kZa2XWSzZf8PVk90ESZUCqXJXnAoGBALsbV6fAkvJANX+3sTFL3ag/zksdvQOQSdmr+9djztB0DqfKjf7OBUr28O/PNAgX6S9bHLhZ64m7IcQN+UtYTAoDbvGB786NhPJzqsF0NlTC6Vq2id/PzMz7r+jOAQk8+OTFHp3EWUlKaK77S5wcT/YzhiCMHAssrZwSsTvY4e9F";
    public static final String RSA_PRIVATE = "";
    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            switch (payResult.getResultStatus()) {
                case "9000":
                    //Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
                    ARouter.getInstance().build(ARouterPathUtils.User_PayStateActivity)
                            .withInt("state", 1)
                            .navigation();
                    break;
                case "8000":
                    Toast.makeText(context, "正在处理中", Toast.LENGTH_SHORT).show();
                    break;
                case "4000":
                    //Toast.makeText(context, "订单支付失败", Toast.LENGTH_SHORT).show();
                    ARouter.getInstance().build(ARouterPathUtils.User_PayStateActivity)
                            .withInt("state", 0)
                            .navigation();
                    break;
                case "5000":
                    Toast.makeText(context, "重复请求", Toast.LENGTH_SHORT).show();
                    break;
                case "6001":
                    Toast.makeText(context, "已取消支付", Toast.LENGTH_SHORT).show();
                    break;
                case "6002":
                    Toast.makeText(context, "网络连接出错", Toast.LENGTH_SHORT).show();
                    break;
                case "6004":
                    Toast.makeText(context, "正在处理中", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    //Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT).show();
                    ARouter.getInstance().build(ARouterPathUtils.User_PayStateActivity)
                            .withInt("state", 0)
                            .navigation();
                    break;
            }
        }
    };

    /**
     * 签名发在客户端来做。
     *
     * @param context
     */

    public void toALiPayByClient(final Activity context) {


        this.context = context;

        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            showAlert(context, "APPID或RSA_PRIVATE未配置");
            return;
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(context);
                Map<String, String> result = alipay.payV2
                        (orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 签名在服务端来做
     *
     * @param context
     * @param orderInfo
     */
    public void toALiPayService(final Activity context, final String orderInfo) {
        this.context = context;
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(context);
                Map<String, String> result = alipay.payV2
                        (orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    private static void showAlert(Context ctx, String info) {
        showAlert(ctx, info, null);
    }


    private static void showAlert(Context ctx, String info, DialogInterface.OnDismissListener onDismiss) {
        new AlertDialog.Builder(ctx)
                .setMessage(info)
                .setPositiveButton("Confirm", null)
                .setOnDismissListener(onDismiss)
                .show();
    }
}
